package com.lindenliu.rememberIt.data
{
	import com.lindenliu.common.classbase.IDestroyManually;
	import com.lindenliu.rememberIt.events.RememberItWordResultEvent;
	
	import flash.events.EventDispatcher;
	
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	[Event(name="wordResult", type="com.lindenliu.rememberIt.events.RememberItWordResultEvent")]
	
	public class WordServer extends EventDispatcher implements IDestroyManually
	{
		private static var wordServer:WordServer;
		private static var queryJobID:uint;
		private static const DICT_URL:String = "http://localhost/dict/ws.php";
		//private static const DICT_URL:String = "http://dict.cn/ws.php";
		
		private var jobs:Object = new Object();
		private var ws:HTTPService = new HTTPService();
		public function WordServer()
		{
			ws.url = DICT_URL;
			ws.resultFormat = "e4x";
			bindListeners();
		}
		public static function getInstance():WordServer
		{
			if ( ! wordServer )
			{
				wordServer = new WordServer();
			}
			return wordServer;
		}
		public function destroy():void
		{
			removeListeners();
		}
		public function queryWord(word:String):uint
		{
			var params:Object = {q:word};
			params["utf8"] = true;
			var jobID:uint = getJobID();
			jobs[ws.send(params)] = jobID;
			return jobID;
		}
		private function bindListeners():void
		{
			ws.addEventListener(ResultEvent.RESULT, ws_onComplete);
		}
		private function removeListeners():void
		{
			ws.removeEventListener(ResultEvent.RESULT, ws_onComplete);
		}
		private function ws_onComplete(event:ResultEvent):void
		{
			var xml:XML = new XML(event.result);
			var queryID:uint = jobs[event.token];
			
			dispatchEvent(new RememberItWordResultEvent(RememberItWordResultEvent.WORD_RESULT, new WordItem(xml), queryID));
		}
		private function getJobID():uint
		{
			return ++queryJobID;
		}
	}
}